var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

var Table = require('../utils/commonDBConn').Table;

var crypto  = require('crypto');


passport.serializeUser(function (user, done) {//保存user对象
  done(null, user);//可以通过数据库方式操作
});

passport.deserializeUser(function (user, done) {//删除user对象
  done(null, user);//可以通过数据库方式操作
});

passport.use(new LocalStrategy(
    function (username, password, done) {
      password = crypto.createHash('md5').update(password).digest('hex').toUpperCase();
      var db = new Table();
      var sql;
      if(isNaN(username)){//非数字或者不可转为数字 为数字的话认为是手机号登录
        sql = 'select * from users where username = ? and password = ?';
      }else{
        sql = 'select * from users where phone = ? and password = ?';
      }


        db.executeSql(sql,[username,password],function(err,result){
          if (result.length==0) {
            return done(null, false, { message: '用户名或密码错误' });
          }
          return done(null, result[0],{ message: '登录成功' });
        });
      /*db.execQuery('select * from users where ? and ?',[{phone:username},{password:password}],function(result){
        if (result.length==0) {
          return done(null, false, { message: '用户名或密码错误' });
        }
        return done(null, result[0],{ message: '登录成功' });
      })*/

    }
));

exports.postlogin = function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err) }
    if (!user) {
      if(req.body.app){
        return res.send(false);
      }
      req.session.messages =  [info.message];
      //return res.redirect('/login.html');
      return res.render('login',{
        msg:'用户名或密码错误！'
      });
    }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      if(req.body.app){//判断是不是手机登录的，手机登录的直接返回登录状态
        return res.send(JSON.stringify(user));
      }
      if(user.usertype==2){//如果是商家用户跳转到订单管理页
        return res.render('index1',{
          user:user
        });
      }
      if(user.usertype==3){//如果是注册用户跳转到订单管理页
        return res.send(false);
      }
      return res.render('index',{
        name:user.username
      });
    });
  })(req, res, next);
};

exports.logout = function(req, res) {
  req.logout();
  if(req.query.app){//如果手机app登录的直接返回user
    return res.send(true);
  }
  //res.redirect('/login.html');
  return res.render('login',{
    msg:''
  });
};

// Simple route middleware to ensure user is authenticated.  Otherwise send to login page.
exports.ensureAuthenticated = function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  //res.render('login')
  return res.render('login',{
    msg:'用户名或密码错误！'
  });
}


// Check for admin middleware, this is unrelated to passport.js
// You can delete this if you use different method to check for admins or don't need admins
exports.ensureAdmin = function ensureAdmin(req, res, next) {
  console.log(req.user);
  if(req.user && req.user.admin === true)
      next();
  else
      res.send(403);
}
